package org.jeecg.common.rc.aop.dicttrans.strategy.ex;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import org.jeecg.common.rc.aop.dicttrans.classutil.ByteBuddyUtil;
import org.jeecg.common.rc.aop.dicttrans.dictaop.DictCode2Name;
import org.jeecg.common.rc.aop.dicttrans.dictaop.entity.TransInfo;
import org.jeecg.common.rc.aop.dicttrans.dictaop.util.TransUtil;
import org.jeecg.common.rc.aop.dicttrans.strategy.TranslationStrategy;
import org.jeecg.common.util.RefUtil;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zjarlin
 * @since 2023/11/8 10:31
 */
public class CollectionStrategy implements TranslationStrategy<Collection<?>> {

    private final Map<String, Object> spelContextMap = new HashMap<>();

    @Override
    public Collection<?> trans(Collection<?> inVOs) {


        if (CollUtil.isEmpty(inVOs)) {
            return inVOs;
        }
        inVOs = inVOs.stream().filter(e -> Objects.nonNull(e) && !RefUtil.isNew(e)).collect(Collectors.toList());
//        boolean b = inVOs.removeIf(e -> {
//            boolean aNull = Objects.isNull(e);
//            boolean aNew = RefUtil.isNew(e);
//            return aNull || aNew;
//        });
        if (CollUtil.isEmpty(inVOs)) {
            return inVOs;
        }
        spelContextMap.put(TransUtil.OUT_VO, inVOs);
        Object next = inVOs.iterator().next();
        //利用bytebuddy递归生成嵌套代理对象
        Object o1 = ByteBuddyUtil.genChildObjectRecursion(next, TransUtil::getNeedAddFields);
        Class<?> afterObjectClass = o1.getClass();
        List<?> collect = inVOs.stream().map(e -> {
            Object convert = Convert.convert(afterObjectClass, e);
            return convert;
        }).collect(Collectors.toList());

        //翻译过程的全部信息都在这里了 对于单个字典翻译,会按照list中所有dictCode分组TransInfo集合 会调用系统字段批量翻译
        Map<Integer, List<TransInfo<DictCode2Name>>> collect1 = collect.stream().flatMap(item -> {
            List<TransInfo<DictCode2Name>> process = TransUtil.process(item);
            return process.stream();
        }).collect(Collectors.groupingBy(TransInfo::getClassificationOfTranslation));
        //转为临时对象List<TransInfo>后批量处理
        /**  处理内置字典翻译*/
        TransUtil.processBuiltInDictionaryTranslation(collect1);
        /** 处理任意表翻译 */
        TransUtil.processAnyTableTranslation(collect1);
        /** 处理spel表达式 */
        TransUtil.processingSpelExpressions(collect1);
        return collect;
    }
}
